import Vue from 'vue';
import md5 from './md5';
import sha1 from './sha1';
import { promises } from 'fs';
import { get } from 'http';
const BASE_URL = './api';

function alertError(error) {
    window.$vue && window.$vue.$message(error)
}

function getError (content) {
    return {
        status: 1,
        content: content || '未知异常',
        data: ''
    }
}

function utf16to8 (str) {
    var out, i, len, c
    out = ''
    len = str.length
    for (i = 0; i < len; i++) {
        c = str.charCodeAt(i)
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i)
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
        } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
        }
    }
    return out
}

async function fetchData(url, method, params, body) {
    params = params ? Object.assign({}, params) : {};

    if (body) {
        try {
            body = JSON.String(body);
        } catch (error) {
    
        }
    }

    let response = await fetch(`${BASE_URL}${url}`, {
        method,
        headers: {
            'Content-Type': 'application/json'
        },
        body,
    });

    if (response.ok) {
        try {
            let json = await response.json();
            if (json.status === 0) {
                return json
            } else if (json.status === 400 || json.status === 404) {
                window.sessionStorage.removeItem('_USER_INFO');
                window.$vue && (window.$vue.$root.userInfo = null);
                window.$vue && window.$vue.$router.push('/login')
            } else {
                alertError(json.content);
                return Promise.reject(json);
            }
        } catch (error) {
            return {}
        }
    } else {
        if (response.status === 500) {
            alertError('服务器异常')
            return Promise.reject(getError('服务器异常'))
        } else {
            alertError('请求失败')
            return Promise.reject(getError('请求失败'))
        }
    }
}

function posts(url, body) {
    return fetchData(url, 'POST', null, body);
}
function gets(url, params) {
    return fetchData(url, 'GET', params, null);
}

Vue.prototype.$post = posts;
Vue.prototype.$get = gets;

export default {
    posts,
    gets
}